package com.superjson.showpro.shared.util;

import com.beantools.constants.Charset;
import com.beantools.util.StringUtil;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;

/**
 * Created By zby on 13:34 2019/6/8
 * 这是密码加密的方法
 */

public class CryptUtil {

    /**
     * 这是加密和解密次数
     */
    private static final int count = 8;

    /**
     * Created By zby on 13:38 2019/6/8
     * 密码加密算法
     *
     * @param msg 待加密的字符串
     */
    public static String encrypt(String msg) {
        return cryptHandler(msg, true);
    }


    /**
     * Created By zby on 13:38 2019/6/8
     * 密码加密算法
     *
     * @param msg 待解密的字符串
     */
    public static String decrypt(String msg) {
        return cryptHandler(msg, false);
    }

    /**
     * Created By zby on 14:13 2019/6/8
     * 这是处理加密和解密的句柄，如果<code>encrypt = true</code>，那么，其就加密，否则，解密
     *
     * @param encrypt true 加密 false 解密
     * @param msg     待价密和解密的字符串
     */

    private static String cryptHandler(String msg, boolean encrypt) {
        if (StringUtil.isBlank(msg)) {
            return null;
        }
        int index = 0;
        String var = msg;
        try {
            while (index < count) {
                var = encrypt ? Base64.encodeBase64String(var.getBytes()) :
                        new String(Base64.decodeBase64(var.getBytes()), Charset.CHARSET);
                index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return var;
    }


}
